<template>
    <div>
        <el-button type="success" @click="openDialog('add')">新增</el-button>

        <span style="font-size: 20px; margin-left: 20px; font-weight: bold">工序列表</span>

        <input ref="fileInput" type="file" style="display: none" @change="handleFileChange" />
        <!-- 工序列表（仅展示序号列相关结构） -->
        <div class="table-container">
            <el-table :data="planList" stripe ref="tableRef" height="300">
                <el-table-column>
                    <template #header>
                        <el-checkbox v-model="allChecked" @change="handleCheckAllChange"></el-checkbox>
                    </template>
                    <template #default="scope">
                        <el-checkbox v-model="checkedIds" :value="scope.row.procedureId"></el-checkbox>
                    </template>
                </el-table-column>
                <el-table-column  type="index" label="序号" width="80"></el-table-column>
                <el-table-column prop="processCode" label="工序编码" width="150"></el-table-column>
                <el-table-column prop="processName" label="工序名称"></el-table-column>
                <el-table-column prop="typeName" label="工序类型"></el-table-column>
                <el-table-column prop="leader" label="负责人"></el-table-column>
                <el-table-column prop="affiliation" label="所属部门" width="100"></el-table-column>
                <el-table-column prop="status" label="状态">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === true ? 'success' : 'danger'">{{ scope.row.status === true ? '启用' : '禁用' }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" width="180"></el-table-column>
                <el-table-column prop="procedureId" label="操作" fixed="right" width="140">
                    <template #default="scope">
                        <el-button type="text" @click="openDialog('edit', scope.row)">编辑</el-button>
                        <el-button type="text" @click="DeleteProductionPlanning(scope.row.procedureId)">删除</el-button>
                        <!-- <el-button type="text" @click="GetByProductionPlanning(scope.row.processTypeId)">详情</el-button> -->
                    </template>
                </el-table-column>
            </el-table>
            <el-button @click="batchDelete">批量删除</el-button>
        </div>
        <!-- 分页部分 -->
        <div class="demo-pagination-block">
            <el-pagination
                v-model:current-page="page.PageIndex"
                v-model:page-size="page.PageSize"
                :page-sizes="[10, 20, 30, 50]"
                :background="true"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total.totalCount"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>

        <!-- 新增/编辑对话框 -->
        <el-dialog
            :title="dialogType === 'add' ? '新增工序' : '编辑工序'"
            v-model="dialogVisible"
            :close-on-click-modal="false"
        >
                <el-form :model="formData" label-width="100px">
                    <el-form-item label="工序编码">
                        <el-input v-model="formData.processCode" disabled placeholder="系统自动生成工序编码"></el-input>
                    </el-form-item>
                    <el-form-item label="工序名称">
                        <el-input v-model="formData.processName"></el-input>
                    </el-form-item>
                    <el-form-item label="工序类型">
                        <el-select
                            v-model="formData.processTypeId"
                            placeholder="请选择工序类型"
                            clearable
                        >
                            <el-option
                                v-for="type in processTypes"
                                :key="type.processTypeId"
                                :label="type.typeName"
                                :value="type.processTypeId"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="负责人">
                        <el-input v-model="formData.leader">
                            <template #suffix>
                                    <el-button size="mini" @click="openOurRepresentativesDialog" >
                                        <i class="el-icon-search" >选择</i>
                                    </el-button>
                                </template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="所属部门">
                        <el-input v-model="formData.affiliation" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="状态">
                        <el-switch v-model="formData.status"></el-switch>
                    </el-form-item>
                    <el-form-item label="备注">
                        <el-input v-model="formData.remark" type="textarea"></el-input>
                    </el-form-item>
                </el-form>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="saveProcessType">确定</el-button>
            </template>
            <el-dialog
            v-model="ourRepresentativesDialogVisible"
            width="500px"
            title="我方代表选择"
            append-to-body
        >
            <el-table
                :data="ourRepresentativesList"
                highlight-current-row
                border
                size="small"
                @current-change="handleOurRepresentativesChange"
            >
                <el-table-column type="index" label="序号" />
                <el-table-column property="userName" label="代表姓名" />
                <el-table-column property="depmentName" label="部门" />
                <el-table-column property="roleName" label="职位" />
            </el-table>
            <template #footer>
                <el-button @click="ourRepresentativesDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="pickOurRepresentatives">确定</el-button>
            </template>
        </el-dialog>
        </el-dialog>
        

    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { write, read } from '@/axios/axiosHelper';
import router from '@/router';

// 定义 API URL 常量
const GET_PROCESS_TYPE_URL = 'http://8.154.44.176:8000/f-read/api/GetProcess/GetProcedure';
const DELETE_PROCESS_TYPE_URL = 'http://8.154.44.176:8000/f-write/api/Process/DelProcedure';
const ADD_PROCESS_TYPE_URL = 'http://8.154.44.176:8000/f-write/api/Process/AddProcedure';
const UPDATE_PROCESS_TYPE_URL = 'http://8.154.44.176:8000/f-write/api/Process/UpdateProcedure';
const GET_PROCESS_CATEGORIES_URL = 'http://8.154.44.176:8000/f-read/api/GetProcess/GetType'; // 新增：获取工序类型的API

// 定义分页对象
const page = ref({
    PageIndex: 1,
    PageSize: 50,
});

// 定义分页总数
const total = ref({
    totalCount: 0,
    totalPage: 0,
});

// 工序列表数据
const planList = ref([]);

// 表格引用
const tableRef = ref(null);

// 全选状态
const allChecked = ref(false);
// 选中的 ID 列表
const checkedIds = ref([]);

// 文件输入引用
const fileInput = ref(null);

// 对话框显示状态
const dialogVisible = ref(false);
// 对话框类型（add 或 edit）
const dialogType = ref('add');
// 表单数据
const formData = reactive({
    procedureId: '',
    processCode: '',
    processName: '',
    processTypeId: '',
    typeName: '',
    leader: '',
    affiliation: '',
    status: true,
    remark: ''
});

// 工序类型列表
const processTypes = ref([]);

// 获取工序列表
const GetProductionPlanning = () => {
    axios.get(GET_PROCESS_TYPE_URL, {
        params: {
            PageIndex: page.value.PageIndex,
            PageSize: page.value.PageSize,
        }
    }).then((res) => {
        if (res.data.code === 200) {
            planList.value = res.data.data.list || [];
            total.value.totalCount = res.data.data.totalCount || 0;
            total.value.totalPage = res.data.data.totalPage || 0;
            // 重置全选状态和选中的 ID 列表
            allChecked.value = false;
            checkedIds.value = [];
        } else {
            ElMessage.error(`获取数据失败：${res.data.message}`);
        }
    }).catch((error) => {
        handleRequestError(error);
    });
};

// 获取工序类型列表
const fetchProcessTypes = () => {
    axios.get(GET_PROCESS_CATEGORIES_URL)
        .then(res => {
            if (res.data.code === 200) {
                processTypes.value = res.data.data || [];
            } else {
                ElMessage.error(`获取工序类型失败：${res.data.message}`);
            }
        })
        .catch(error => {
            handleRequestError(error);
        });
};

// 分页相关方法
const handleSizeChange = (val) => {
    page.value.PageSize = val;
    GetProductionPlanning();
};

const handleCurrentChange = (val) => {
    page.value.PageIndex = val;
    GetProductionPlanning();
};

// 生命周期钩子：组件挂载后获取数据
onMounted(() => {
    fetchBaseData();
    GetProductionPlanning();
    fetchProcessTypes(); // 新增：获取工序类型
});

// 我方代表列表
const ourRepresentativesList = ref([]);
const currentOurRepresentative = ref(null);
const ourRepresentativesDialogVisible = ref(false);

// 获取基础数据
const fetchBaseData = () =>{
    axios.get('http://8.154.44.176:8000/r-read/api/Depment/GetDepUserRole')
      .then(res => ourRepresentativesList.value = res.data.data || [])
      .catch(error => {
            ElMessage.error('加载我方代表失败');
            console.error(error);
        });
}

// 打开工序负责人对话框
const openOurRepresentativesDialog = () => {
    if (ourRepresentativesList.value.length === 0) {
        ElMessage.warning('工序负责人数据加载中，请稍后重试');
        return;
    }
    ourRepresentativesDialogVisible.value = true;
};

// 处理工序负责人行选中
const handleOurRepresentativesChange = (val) => {
    currentOurRepresentative.value = val;
};

// 选择工序负责人并填充数据
const pickOurRepresentatives = () => {
    if (currentOurRepresentative.value) {
        formData.leader = currentOurRepresentative.value.userName; // 修改：更新formData中的leader字段
        formData.affiliation = currentOurRepresentative.value.depmentName; // 修改：更新formData中的affiliation字段
        ourRepresentativesDialogVisible.value = false;
    } else {
        ElMessage.warning('请选择一个我方代表');
    }
};

// 跳转详情页面
const GetByProductionPlanning = (processTypeId) => {
    router.push({
        name: 'GetBYIddetailView',
        query: {
            processTypeId: processTypeId
        }
    });
    console.log(processTypeId);
};

// 处理请求错误
const handleRequestError = (error) => {
    if (error !== 'cancel') {
        console.error('请求错误:', error);
        ElMessage.error('请求失败，请检查网络或联系管理员');
    }
};

// 删除单条记录
const DeleteProductionPlanning = async (procedureId) => {
    try {
        const confirmResult = await ElMessageBox.confirm(
            '确认删除该条记录？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        if (confirmResult === 'confirm') {
            const response = await axios.post(
                DELETE_PROCESS_TYPE_URL,
                {
                    procedureIds: procedureId.toString()
                }
            );
            if (response.data.code === 200) {
                ElMessage.success('删除成功');
                GetProductionPlanning();
            } else {
                ElMessage.error(`删除失败：${response.data.message}`);
            }
        }
    } catch (error) {
        handleRequestError(error);
    }
};

// 处理全选
const handleCheckAllChange = (value) => {
    if (value) {
        checkedIds.value = planList.value.map(item => item.procedureId);
    } else {
        checkedIds.value = [];
    }
    allChecked.value = value;
};

// 批量删除
const batchDelete = async () => {
    if (checkedIds.value.length === 0) {
        ElMessage.warning('请选择要删除的记录');
        return;
    }
    try {
        const confirmResult = await ElMessageBox.confirm(
            '确认删除选中的记录？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );
        if (confirmResult === 'confirm') {
            const ids = checkedIds.value.join(',');
            const response = await axios.post(
                DELETE_PROCESS_TYPE_URL,
                {
                    procedureIds: ids
                }
            );
            if (response.data.code === 200) {
                ElMessage.success('批量删除成功');
                GetProductionPlanning();
            } else {
                ElMessage.error(`批量删除失败：${response.data.message}`);
            }
        }
    } catch (error) {
        handleRequestError(error);
    }
};

// 打开对话框
const openDialog = (type, row = null) => {
    dialogType.value = type;
    if (type === 'add') {
        // 清空表单数据
        Object.assign(formData, {
            procedureId: '',
            processCode: '',
            processName: '',
            processTypeId: '',
            leader: '',
            affiliation: '',
            status: true,
            remark: ''
        });
    } else if (type === 'edit') {
        // 反填数据
        Object.assign(formData, {
            procedureId: row.procedureId,
            processCode: row.processCode,
            processName: row.processName,
            processTypeId: row.processTypeId,
            leader: row.leader,
            affiliation: row.affiliation,
            status: row.status,
            remark: row.remark
        });
    }
    dialogVisible.value = true;
};

// 保存工序
const saveProcessType = async () => {
    // 验证工序类型是否已选择
    if (!formData.processTypeId && dialogType.value === 'add') {
        ElMessage.warning('请选择工序类型');
        return;
    }
    
    let url = '';
    if (dialogType.value === 'add') {
        url = ADD_PROCESS_TYPE_URL;
    } else if (dialogType.value === 'edit') {
        url = UPDATE_PROCESS_TYPE_URL;
    }
    try {
        const response = await axios.post(url, formData);
        if (response.data.code === 200) {
            ElMessage.success(dialogType.value === 'add' ? '新增成功' : '编辑成功');
            dialogVisible.value = false;
            GetProductionPlanning();
        } else {
            ElMessage.error(`${dialogType.value === 'add' ? '新增' : '编辑'}失败：${response.data.message}`);
        }
    } catch (error) {
        handleRequestError(error);
    }
};

// 处理文件上传
const handleFileChange = (e) => {
    const file = e.target.files[0];
    if (file) {
        console.log('上传文件:', file);
        // 这里可以添加文件上传逻辑
        ElMessage.info('文件上传功能尚未完全实现');
    }
    // 重置文件输入，允许重复选择同一文件
    fileInput.value.value = '';
};

// 导出方法，供父组件调用
const exports = {
    refreshList: GetProductionPlanning
};
</script>

<style scoped>
.table-container {
    max-height: 400px; /* 固定表格最大高度 */
    overflow-y: auto; /* 超出高度显示滚动条 */
    margin-bottom: 20px; /* 为分页预留空间 */
}

.el-table {
    width: 100%; /* 表格宽度占满容器 */
}

/* 操作记录表格样式 */
.el-dialog .el-table {
    width: 100%;
}

.el-dialog .el-pagination {
    margin-top: 20px;
    text-align: right;
}
</style>    